import axios from 'axios';
import store from './store';
// 创建 axios 实例
const axiosobject = axios.create({
  baseURL: window.server_url,
    timeout: 500000,
    // headers: { 
    //   'Content-Type': 'application/json;charset=utf-8' 
    // }
});
axiosobject.interceptors.request.use(
  config => {
    config.headers = {
      "Content-Type": " application/json"
    };
    if (config.auth=='true' && store.state.token_object.token) {
      config.headers.Authorization = store.state.token_object.token;
      delete config.auth
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);
axiosobject.interceptors.response.use(
  (response)=> {
    if(response.headers && response.headers.authorization ){
      store.state.token_object.token=response.headers.authorization
    }
    return response;
  },
  (error)=> {
    return Promise.reject(error);
  }
);
async function axios_get(url, qs = {}, auth = false, onlyresult = true, timeout=0){
  let config={ 
    params: qs,
    timeout: timeout
  }
  if(auth==true){config.auth='true'}
  return await axios_main(url,null,config,"get",onlyresult)
}
async function axios_main(url, qs, config, type = "get", onlyresult = true){
  let databack=undefined
  try{
    if(type=="get"){
      databack=await axiosobject.get(url,config)
    }
    else if(type=="post"){
      databack=await axiosobject.post(url,qs,config)
    }
    if(databack?.status==200){
      // const {status,message,result } = databack?.data;
      if(onlyresult){
        return databack?.data?.result;
      }
      else{
        return databack?.data;
      }
    }
    else{
     console.log("net error")
    }
  }
  catch(error){
    // console.log(error)
  }
}
async function axios_post(url, qs = {}, auth = false, onlyresult = true, timeout = 0){
  let config={
    timeout: timeout
  }
  if(auth==true){config.auth='true'}
  return await axios_main(url,qs,config,"post",onlyresult) 
}
export function axios_set(){
  global["vapp"].config.globalProperties.$axios_get =axios_get
  global["vapp"].config.globalProperties.$axios_post =axios_post
}